import React, { useState, useRef } from 'react';
import { Modal, Button } from 'antd';
import Draggable from 'react-draggable';

const Index = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [bounds, setBounds] = useState({
    left: 0,
    top: -0,
    bottom: 0,
    right: 0,
  });
  const draggleRef = useRef(null);
  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    setIsModalVisible(false);
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };
  const onStart = (event, uiData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    // 这个方法返回一个矩形对象，包含四个属性：left、top、right和buttom。分别表示元素各边与页面各边的距离
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };

  return (
    <>
      <Button type="primary" onClick={showModal}>
        Open Modal
      </Button>
      <Modal
        title="Basic Modal"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        // Modal 对于是 Modal中content部分
        modalRender={(content) => {
          return (
            <Draggable disabled={false} bounds={bounds} onStart={onStart}>
              <div ref={draggleRef}>{content}</div>
            </Draggable>
          );
        }}
      >
        <p>Some contents...</p>
        <p>Some contents...</p>
        <p>Some contents...</p>
      </Modal>
    </>
  );
};

export default Index;
